package com.zzyk.main.service.impl;


import com.zzyk.main.utils.SpringContextUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;

import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;

/**
 * @author wss_PC
 * @DESCRIPTION FileService 实现类
 * @create 2020-4-8
 */
@Service
public class FileServiceImpl  {

    /**
     * 将图片上传到ftp服务器中
     * @param file
     * @return
     */

    public String fileUpload(MultipartFile file,String path) throws IOException {
        //创建文件保存的目录
        File src=new File(path);
        //判断目录是否存在  不存在就创建
        if(!src.exists()){
            src.mkdirs();
        }
        //保存时的文件名
        DateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
        Calendar calendar = Calendar.getInstance();
        String dateName = df.format(calendar.getTime()) + file.getOriginalFilename();
        System.out.println(dateName);
        //保存文件的绝对路径
        WebApplicationContext webApplicationContext = (WebApplicationContext) SpringContextUtils.applicationContext;
        ServletContext servletContext = webApplicationContext.getServletContext();
        String realPath = servletContext.getRealPath("/");
//                String filePath = realPath + "WEB-INF" + File.separator + "classes" + File.separator + "static" + File.separator + "resource" + File.separator + dateName;
//        String filePath = realPath +  "resource"+File.separator +dateName;
        String filePath = src +File.separator +dateName;
        System.out.println("绝对路径:" + filePath);
        File newFile = new File(filePath);
        //MultipartFile的方法直接写文件

            newFile.setWritable(true);
            //上传文件
            file.transferTo(newFile);

            //数据库存储的相对路径
//            String projectPath = servletContext.getContextPath();
//            HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
//            String contextpath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + projectPath;
            String url =  "/" + dateName;
            System.out.println("相对路径:" + url);
            //文件名与文件URL存入数据库表
            return url;


    }


}